package com.it.controller;

import com.it.common.ResultResponse;
import com.it.common.ResultUtils;
import com.it.enums.ErrorCode;
import com.it.exception.BusinessException;
import com.it.model.entity.User;
import com.it.service.UserService;
import com.it.utils.UpLoadFile;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private UpLoadFile upLoadFile;

    @Resource
    private UserService userService;

    @PostMapping("/upload")
    @ApiOperation(value = "头像文件上传到OSS")
    public ResultResponse<String> uploadAvatar(MultipartFile file, HttpServletRequest request) {

        if (file == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "文件上传为空~");
        }

        User loginUser = userService.getCurrentLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH, "请先登录账号~~~");
        }

        // 上传到阿里云对象存储
        String resultUrl = "";
        try {
            resultUrl = upLoadFile.uploadFile(file);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败~");
        }

        // 将生成的头像url存入数据库
        User user = new User();
        user.setId(loginUser.getId());
        user.setAvatarUrl(resultUrl);
        boolean successFlag = userService.updateById(user);
        if (!successFlag) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "头像上传失败");
        }
        return ResultUtils.success(resultUrl);
    }
}
